from rest_framework import serializers

from apps.users.models import User


class UserGetInfoSerializer(serializers.ModelSerializer):
    # 根据 User 模型表 生成对应的序化器
    class Meta:
        model = User
        fields = ("id", "username", "mobile", "email")


class UserPostInfoSerializer(serializers.ModelSerializer):
    # 定义额外字段 只做序列化输出
    password2 = serializers.CharField(write_only=True)

    class Meta:
        model = User
        # 自定义字段必须添加到fields
        fields = ("username", "password", "mobile", "email", "password2")
        # 反序化不显示密码 增加额外属性
        extra_kwargs = {
            "password": {"write_only": True}
        }

    # 重写字段校验
    def validate(self, attrs):
        if attrs.get("password") != attrs.get("password2"):
            raise serializers.ValidationError("两次密码输入不一致")
        return attrs

    # 重写写入数据方法
    def create(self, validated_data):
        # 去除 模型中没有的字段
        del validated_data["password2"]
        user = User.objects.create_user(**validated_data)
        return user

